import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }

class UsernameMobileAuthBackend(ModelBackend):
    # 重写Django原有的验证方法
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 捕获异常
        try:
        # 判断是否是手机号
            if re.match(r"^1[3-9]\d{9}$",username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except:
            user = None
        # 验证密码(如果不是None且密码验证通过了 返回user)
        if user is not None and user.check_password(password):
            return user